package plus.lgx.textsearcher;

import lombok.SneakyThrows;

import java.io.*;
import java.util.Optional;

/**
 * Class name: FileCleanUp
 *
 * Create time: 1/2/23 9:01 PM
 *
 * @author lgx
 * @version 1.0
 */
public class FileCleanUp {

    Writer fr;
    int cnt = 0;
    int brokenCnt = 0;

    {
        try {
            fr = new FileWriter("/home/lgx/Music/brokenMusic");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

//    @Test
    public void cleanUpBrokenMusic() throws IOException {
        cleanUpBrokenMusic(new File("/home/lgx/Music"));
        fr.close();
        System.out.println(cnt);
        System.out.println(brokenCnt);
    }

    public void cleanUpBrokenMusic(File f) throws IOException {
        File[] files = Optional.ofNullable(f.listFiles()).orElse(new File[0]);
        outer: for (File file : files) {
            if (file.isFile()) {
                cnt++;
                try (InputStream fis = new FileInputStream(file)) {
                    byte[] bytes = fis.readNBytes(50);
                    for (byte b : bytes) {
                        if (b != -1) continue outer;
                    }
                    brokenCnt++;
                    file.deleteOnExit();
                    fr.append(file.getAbsolutePath()).append('\n');
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (file.isDirectory()) {
                cleanUpBrokenMusic(file);
                String[] list = file.list();
                if (list == null || list.length == 0) {
                    fr.append("dir: ").append(file.getAbsolutePath()).append('\n');
                    file.deleteOnExit();
                }
            }
        }
    }

}
